<?php
class Ynbusinesspages_IndexController extends Core_Controller_Action_Standard {
	public function indexAction() {
		$this -> _helper -> content -> setNoRender() -> setEnabled();
	}

	public function listingAction() {
		$this -> _helper -> content -> setNoRender() -> setEnabled();
	}

	public function manageAction() {
		$this -> _helper -> content -> setEnabled();
	}
    
	public function getMyLocationAction()
	{
		$latitude = $this -> _getParam('latitude');
		$longitude = $this -> _getParam('longitude');
		$values = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=$latitude,$longitude&sensor=true");
		echo $values;
		die ;
	}
	
	public function addInfoAction()
	{
		// Disable layout and viewrenderer
		$this -> _helper -> layout -> disableLayout();
		$label_header = 'header_'.$this->_getParam('index');
		$label_content = 'content_'.$this->_getParam('index');
		$this -> view -> form = $form = new Ynbusinesspages_Form_Business_AddInfo(array('labelHeader' => $label_header, 'labelContent' => $label_content));
	}

	public function createAction() {
		$this -> _helper -> content -> setEnabled();

		// Return if guest try to access to create link.
		if (!$this -> _helper -> requireUser -> isValid())
			return;

		// Check authorization to post job.
		if (!$this -> _helper -> requireAuth() -> setAuthParams('ynbusinesspages_business', null, 'create') -> isValid())
			return;

		$isCreator = Engine_Api::_() -> getDbTable('creators', 'ynbusinesspages') -> checkIsCreator();
		if (!$isCreator) {
			$this -> _helper -> redirector -> gotoRoute(array('module' => 'ynbusinesspages', 'controller' => 'index', 'action' => 'create-step-one'), 'ynbusinesspages_general', TRUE);
		}

	}

	public function createStepOneAction() {
		//    $this -> _helper -> content -> setEnabled();

		// Return if guest try to access to create link.
		if (!$this -> _helper -> requireUser -> isValid())
			return;

		// Check authorization to post job.
		if (!$this -> _helper -> requireAuth() -> setAuthParams('ynbusinesspages_business', null, 'create') -> isValid())
			return;

		$table = Engine_Api::_() -> getItemTable('ynbusinesspages_package');
		$select = $table -> select() -> where('`show` = 1') -> where('`deleted` = 0') -> where('`current` = 1') -> order('order ASC');
		$packages = $table -> fetchAll($select);
		$this -> view -> packages = $packages;
	}

	public function createStepTwoAction() {
		// Return if guest try to access to create link.
		if (!$this -> _helper -> requireUser -> isValid())
			return;

		//TODO Check authorization to create business.

		//$this -> _helper -> content -> setEnabled();
		$viewer = Engine_Api::_() -> user() -> getViewer();
		
		//get first industry
		$tableCategory = Engine_Api::_() -> getItemTable('ynbusinesspages_category');
		$categories = $tableCategory -> getCategories();
		$firstCategory = $categories[1];
		$category_id = $this -> _getParam('category_id', $firstCategory -> category_id);

		// Create Form
		//get current category
		$category = Engine_Api::_() -> getItem('ynbusinesspages_category', $category_id);

		//get profile question
		$topStructure = Engine_Api::_() -> fields() -> getFieldStructureTop('ynbusinesspages_business');
		if (count($topStructure) == 1 && $topStructure[0] -> getChild() -> type == 'profile_type') {
			$profileTypeField = $topStructure[0] -> getChild();
			$formArgs = array('topLevelId' => $profileTypeField -> field_id, 'topLevelValue' => $category -> option_id);
		}

		$this -> view -> form = $form = new Ynbusinesspages_Form_Create( array('formArgs' => $formArgs));

		// Populate industry list.
		$categories = $tableCategory -> getCategories();
		unset($categories[0]);
		foreach ($categories as $item) {
			$form -> category_id -> addMultiOption($item['category_id'], str_repeat("-- ", $item['level'] - 1) . $item['title']);
		}

		//populate category
		if ($category_id) {
			$form -> category_id -> setValue($category_id);
		} else {
			$form -> addError('Create business require at least one category. Please contact admin for more details.');
		}


		$submit_button = $this -> _getParam('submit_button');
		if (!isset($submit_button)) {
			$form -> populate($form -> getValues());
			return;
		}
		
		// Check method and data validity.
		$posts = $this -> getRequest() -> getPost();
		if (!$this -> getRequest() -> isPost()) {
			return;
		}
		if (!$form -> isValid($posts)) {
			return;
		}

		//get values
		$params = $this -> _getAllParams();
		$values = $form -> getValues();

		//check sponsor
		if ($values['sponsor'] == 1) {
			if (empty($values['sponsor_period'])) {
				$form -> addError('Please input valid sponsor period value.');
				return;
			}
		}

		//check from & to employee value
		if ($values['to'] < $values['from']) {
			$form -> addError('Please input valid from employee & to employee value.');
			return;
		}

		$regexp = "/^[A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/";
		if (!preg_match($regexp, $values['contact_email'])) {
			$form -> addError('Please enter valid email!');
			return;
		}
		$db = Engine_Db_Table::getDefaultAdapter();
		$db -> beginTransaction();
		try {
			//save company
			$companyTable = Engine_Api::_() -> getItemTable('ynjobposting_company');
			$company = $companyTable -> createRow();
			$company -> user_id = $viewer -> getIdentity();
			$company -> name = $values['name'];
			$company -> description = $values['description'];
			$company -> location = $values['location_address'];
			$company -> longitude = $values['long'];
			$company -> latitude = $values['lat'];
			$company -> website = $values['website'];
			$company -> from_employee = $values['from'];
			$company -> to_employee = $values['to'];
			$company -> contact_name = $values['contact_name'];
			$company -> contact_email = $values['contact_email'];
			$company -> contact_phone = $values['contact_phone'];
			$company -> contact_fax = $values['contact_fax'];
			$company -> save();

			// Set photo
			if (!empty($values['photo'])) {
				$company -> setPhoto($form -> photo);
			}

			// Add Cover photo
			if (!empty($values['cover_thumb'])) {
				$company -> setCoverPhoto($form -> cover_thumb);
			}

			// Insert Addtional Information
			$tableCompanyInfo = Engine_Api::_() -> getDbTable('companyinfos', 'ynjobposting');
			$number_add_more = $params['number_add_more'];
			for ($i = 1; $i <= $number_add_more; $i++) {
				$header = $params['header_' . $i];
				$content = $params['content_' . $i];
				if (!empty($header) && !empty($content)) {
					$allowed_html = '<strong><b><em><i><u><strike><sub><sup><p><div><pre><address><h1><h2><h3><h4><h5><h6><span><ol><li><ul><a><img><embed><br><hr><object><param><iframe>';
					$infoRow = $tableCompanyInfo -> createRow();
					$infoRow -> header = strip_tags($header, $allowed_html);
					$infoRow -> content = strip_tags($content, $allowed_html);
					$infoRow -> company_id = $company -> getIdentity();
					$infoRow -> save();
				}
			}

			//insert industry to mapping table
			if (!empty($values['industry_id'])) {
				$tableIndustryMap = Engine_Api::_() -> getDbTable('industrymaps', 'ynjobposting');
				$checkIndustry = $tableIndustryMap -> checkExistIndustryByCompany($values['industry_id'], $company -> getIdentity());
				if (empty($checkIndustry)) {
					$rowIndustryMap = $tableIndustryMap -> createRow();
					$rowIndustryMap -> company_id = $company -> getIdentity();
					$rowIndustryMap -> industry_id = $values['industry_id'];
					$rowIndustryMap -> main = true;
					$rowIndustryMap -> save();
				}
				$sub_industries = $this -> _getParam('sub_industry');
				if (!empty($sub_industries)) {
					foreach ($sub_industries as $sub_industry_id) {
						$checkIndustry = $tableIndustryMap -> checkExistIndustryByCompany($sub_industry_id, $company -> getIdentity());
						if (empty($checkIndustry)) {
							$rowIndustryMap = $tableIndustryMap -> createRow();
							$rowIndustryMap -> company_id = $company -> getIdentity();
							$rowIndustryMap -> industry_id = $sub_industry_id;
							$rowIndustryMap -> main = false;
							$rowIndustryMap -> save();
						}
					}
				}
			}

			//save custom field values of industries
			$customfieldform = $form -> getSubForm('fields');
			$customfieldform -> setItem($company);
			$customfieldform -> saveValues();

			//send notice to admin
			$notifyApi = Engine_Api::_() -> getDbtable('notifications', 'activity');
			$list_admin = Engine_Api::_() -> user() -> getSuperAdmins();
			foreach ($list_admin as $admin) {
				$notifyApi -> addNotification($admin, $company, $company, 'ynjobposting_company_create');
			}

			//add activity
			$activityApi = Engine_Api::_() -> getDbtable('actions', 'activity');
			$action = $activityApi -> addActivity($company -> getOwner(), $company, 'ynjobposting_company_create');
			if ($action) {
				$activityApi -> attachActivity($action, $company);
			}

			//set auth for view, comment
			$auth = Engine_Api::_() -> authorization() -> context;
			$roles = array('owner', 'owner_member', 'network', 'registered', 'everyone');
			$auth_arr = array('view', 'comment');
			foreach ($auth_arr as $elem) {
				$auth_role = $values[$elem];
				if (!$auth_role) {
					$auth_role = 'everyone';
				}
				$roleMax = array_search($auth_role, $roles);
				foreach ($roles as $i => $role) {
					$auth -> setAllowed($company, $role, $elem, ($i <= $roleMax));
				}
			}
			// Commit
			$db -> commit();

			if (Engine_Api::_() -> hasModuleBootstrap("yncredit")) {
				Engine_Api::_() -> yncredit() -> hookCustomEarnCredits($company -> getOwner(), $company -> name, 'ynjobposting_company', $company);
			}

		} catch (Exception $e) {
			$db -> rollBack();
			throw $e;
		}

		if ($values['sponsor'] == 1) {
			return $this -> _forward('success', 'utility', 'core', array('parentRedirect' => Zend_Controller_Front::getInstance() -> getRouter() -> assemble(array('controller' => 'company', 'action' => 'place-order', 'number' => $values['sponsor_period'], 'id' => $company -> getIdentity()), 'ynjobposting_extended', true), 'messages' => array(Zend_Registry::get('Zend_Translate') -> _('Please wait...'))));
		} else {
			return $this -> _forward('success', 'utility', 'core', array('parentRedirect' => Zend_Controller_Front::getInstance() -> getRouter() -> assemble(array('controller' => 'company', 'action' => 'detail', 'id' => $company -> getIdentity()), 'ynjobposting_extended', true), 'messages' => array(Zend_Registry::get('Zend_Translate') -> _('Please wait...'))));
		}

	}

	public function claimAction() {
		$this -> _helper -> content -> setNoRender() -> setEnabled();
	}

}
